<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">



  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico?v=5.1.4">






  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="7.1 删除模型的注意事项1.204 的HTTP状态码代表的是NO CONTENT，无内容。所以如果状态码是204，那么无论返回什么，前端都接受不到，但是我们要尽量返回格式化的信息，让前端能够判断，为此，我们可以使用状态码202，并且添加一个特殊的error_code=-1 来代表删除操作 2.由于我们的删除是逻辑删除，使用get的方法会一直可以查询出当前用户，这里我们应该使用filter_by(">
<meta property="og:type" content="article">
<meta property="og:title" content="Flask构建可扩展的RESTful-API-7--权限控制">
<meta property="og:url" content="http://imwl.ml/flask-api/Flask构建可扩展的RESTful-API-7--权限控制/index.html">
<meta property="og:site_name" content="Get busy living">
<meta property="og:description" content="7.1 删除模型的注意事项1.204 的HTTP状态码代表的是NO CONTENT，无内容。所以如果状态码是204，那么无论返回什么，前端都接受不到，但是我们要尽量返回格式化的信息，让前端能够判断，为此，我们可以使用状态码202，并且添加一个特殊的error_code=-1 来代表删除操作 2.由于我们的删除是逻辑删除，使用get的方法会一直可以查询出当前用户，这里我们应该使用filter_by(">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/14597179-c5171f4d51fe6475?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2019-04-14T14:46:34.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Flask构建可扩展的RESTful-API-7--权限控制">
<meta name="twitter:description" content="7.1 删除模型的注意事项1.204 的HTTP状态码代表的是NO CONTENT，无内容。所以如果状态码是204，那么无论返回什么，前端都接受不到，但是我们要尽量返回格式化的信息，让前端能够判断，为此，我们可以使用状态码202，并且添加一个特殊的error_code=-1 来代表删除操作 2.由于我们的删除是逻辑删除，使用get的方法会一直可以查询出当前用户，这里我们应该使用filter_by(">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/14597179-c5171f4d51fe6475?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://imwl.ml/flask-api/Flask构建可扩展的RESTful-API-7--权限控制/">





  <title>Flask构建可扩展的RESTful-API-7--权限控制 | Get busy living</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>
	

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Get busy living</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Stay Hungry,Stay Foolish</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-gitbook">
          <a href="/book/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br>
            
            gitbook
          </a>
        </li>
      
        
        <li class="menu-item menu-item-resume">
          <a href="/resume/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-address-card"></i> <br>
            
            个人简历
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://imwl.ml/flask-api/Flask构建可扩展的RESTful-API-7--权限控制/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="WeiLai">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Get busy living">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Flask构建可扩展的RESTful-API-7--权限控制</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-12-18T18:36:16+08:00">
                2018-12-18
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/flask-api/" itemprop="url" rel="index">
                    <span itemprop="name">flask-api</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="7-1-删除模型的注意事项"><a href="#7-1-删除模型的注意事项" class="headerlink" title="7.1 删除模型的注意事项"></a>7.1 删除模型的注意事项</h1><p>1.204 的HTTP状态码代表的是NO CONTENT，无内容。所以如果状态码是204，那么无论返回什么，前端都接受不到，但是我们要尽量返回格式化的信息，让前端能够判断，为此，我们可以使用状态码202，并且添加一个特殊的error_code=-1 来代表删除操作</p>
<p>2.由于我们的删除是逻辑删除，使用get的方法会一直可以查询出当前用户，这里我们应该使用filter_by()，传入status=1，好在，我们之前已经在基类重写了filter_by()，所以我们只需要调用filter_by()传入id即可<br>app\api\v1\user.py<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">@api.route(&apos;/&lt;int:uid&gt;&apos;, methods = [&apos;DELETE&apos;]) </span><br><span class="line">@auth.login_required</span><br><span class="line">def delete_user(uid):</span><br><span class="line">    with db.auto_commit():</span><br><span class="line">        # user = User.query.get_or_404(uid)   #软删除后，用get 还是能查询到，所以改写</span><br><span class="line">        user = User.query.filter_by(id=uid).first_or_404()</span><br><span class="line">        user.delete()     #  软删除</span><br><span class="line">    # return &apos;delete sucess&apos;</span><br><span class="line">    return DeleteSuccess()</span><br></pre></td></tr></table></figure></p>
<p>app\libs\erro_code.py<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">class DeleteSuccess(Success):</span><br><span class="line">    code = 202</span><br><span class="line">    error_code = 1</span><br></pre></td></tr></table></figure></p>
<p>3.防止超权现象 id=1的用户，不能删除id=2的用户，为了解决这个问题，我们的uid不能由用户传入，而是应该从他传入的token中取出来。由于我们之前做token验证的时候，已经把取出来的信息存入到了flask的g中，所以我们只需要从g中取出来做判断即可<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">@api.route(&apos;&apos;, methods = [&apos;DELETE&apos;])   </span><br><span class="line">@auth.login_required</span><br><span class="line">def delete_user():</span><br><span class="line">    uid = g.user.uid   #  防止超权，从token中读取  已存储在 g 变量中 ，g 变量线程隔离。</span><br><span class="line">                    # 对于管理员来说，可以超权，删除别的用户</span><br><span class="line"></span><br><span class="line">    with db.auto_commit():</span><br><span class="line"></span><br><span class="line">        # user = User.query.get_or_404(uid)   #软删除后，用get 还是能查询到，所以改写</span><br><span class="line">        user = User.query.filter_by(id=uid).first_or_404()</span><br><span class="line">        user.delete()     #  软删除</span><br><span class="line">    # return &apos;delete sucess&apos;</span><br><span class="line">    return DeleteSuccess()</span><br></pre></td></tr></table></figure></p>
<blockquote>
<p>两个知识点<br>1.g.user.uid之所以可以这样用.的方式获取uid，是因为我们在向g中存储user的时候，使用的是namedtuple，而不是dict，不然我们就只能g.user[‘uid’]这样获取了<br>2.即使两个用户同时访问这个接口，我们也不会出错，g会正确的指向每一个请求的user，这是因为g是线程隔离的</p>
</blockquote>
<p>4.我们是需要一个超级管理员用户的试图函数super_delete_user，可以通过传入uid来删除指定用户的。但是对这两个接口，普通用户应该只能访问delete_user，而超级管理员都能够访问。</p>
<p>首先我们需要创建一个管理员用户，不过管理员用户不能通过公开API来创建，而应该直接在数据库里创建，但是这又涉及到一个问题，就是直接在数据库里创建，密码不好生成。所以最好的方式是创建一个离线脚本文件.也可以普通注册，改auth为2<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">from app import create_app</span><br><span class="line">from app.models.base import db</span><br><span class="line">from app.models.user import User</span><br><span class="line"></span><br><span class="line">app = create_app()</span><br><span class="line">with app.app_context():</span><br><span class="line">    with db.auto_commit():</span><br><span class="line">        # 离线脚本，创建一个超级管理员</span><br><span class="line">        user = User()</span><br><span class="line">        user.nickname = &apos;Super&apos;</span><br><span class="line">        user.password = &apos;123456&apos;</span><br><span class="line">        user.email = &apos;999@qq.com&apos;</span><br><span class="line">        user.auth = 2</span><br><span class="line">        db.session.add(user)</span><br><span class="line"></span><br><span class="line"># 直接运行就能创建</span><br></pre></td></tr></table></figure></p>
<p>这个脚本不仅仅可以生成管理员，还可以使用它生成大量的假数据，测试数据</p>
<h1 id="7-2-权限管理方案"><a href="#7-2-权限管理方案" class="headerlink" title="7.2 权限管理方案"></a>7.2 权限管理方案</h1><p>通过之前的分析，我们可以发现，我们之前的get_user，实际上应该是super_get_user，而我们应该在多添加一个get_user作为普通用户的获取方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">@api.route(&apos;/&lt;int:uid&gt;&apos;, methods=[&apos;GET&apos;])</span><br><span class="line">@auth.login_required</span><br><span class="line">def super_get_user(uid):</span><br><span class="line">    user = User.query.filter_by(id=uid).first_or_404(uid)</span><br><span class="line">    return jsonify(user)</span><br><span class="line"></span><br><span class="line">@api.route(&apos;&apos;, methods = [&apos;GET&apos;])   </span><br><span class="line">@auth.login_required</span><br><span class="line">def get_user():</span><br><span class="line">    uid = g.user.uid </span><br><span class="line">    user = User.query.filter_by(id=uid).first_or_404()</span><br><span class="line">    return jsonify(user)</span><br></pre></td></tr></table></figure></p>
<h3 id="1-不太好的权限管理方案"><a href="#1-不太好的权限管理方案" class="headerlink" title="1.不太好的权限管理方案"></a>1.不太好的权限管理方案</h3><p>我们只要可以在视图函数中获取到用户的权限，就可以根据权限来判断，用户的身份，来做出不同的控制。</p>
<p>要做到这一点，我们只需要在生成令牌的时候，将is_admin的字段写入到token中。然后再视图函数中取出这个字段来进行不同的判断就好了。</p>
<p>这样的方案有两个缺点： 1.代码太啰嗦了，每个视图函数都需要做这样的判断。 2.我们把全新想的太简单了，我们这个项目只有管理员和普通用户两种，但是真正的权限应该有各种分组，每个分组每个用户都有不同的权限，如果这样，再在视图函数里进行控制基本上是不可能</p>
<h3 id="2-比较好的权限管理方案"><a href="#2-比较好的权限管理方案" class="headerlink" title="2.比较好的权限管理方案"></a>2.比较好的权限管理方案</h3><p>假如说我们在代码里做三张表（Mysql，Redis，配置文件），每一张表都记录着某一种权限，现在假如某一个请求过来了。当用户访问@auto.login的接口的话，他必须要带有一个token令牌中的，而我们是可以从token中读取到当前的权限种类的，并且我们是可以知道他所访问的接口的。我们可以拿权限种类和接口做匹配，然后来做判断。 这样做还有一个很好的优势，是我们可以在进入方法前进行权限判断，如果不能够访问根本就不会进入该方法。</p>
<p><img src="http://upload-images.jianshu.io/upload_images/14597179-c5171f4d51fe6475?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image"> </p>
<h1 id="7-3-Scope权限管理的实现"><a href="#7-3-Scope权限管理的实现" class="headerlink" title="7.3 Scope权限管理的实现"></a>7.3 Scope权限管理的实现</h1><h2 id="遇到的坑"><a href="#遇到的坑" class="headerlink" title="遇到的坑"></a>遇到的坑</h2><p>用的之前生成的token，当时token并没有写入scope,所以报错重新生成就好了。</p>
<h3 id="1-编码实现"><a href="#1-编码实现" class="headerlink" title="1.编码实现"></a>1.编码实现</h3><p>根据上一小节的编写，我们来动手编写权限管理方案</p>
<h4 id="1-1-scope配置"><a href="#1-1-scope配置" class="headerlink" title="1.1 scope配置"></a>1.1 scope配置</h4><p>app/libs/scope.py<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">class AdminScope:</span><br><span class="line">    allow_api = [&apos;v1.super_get_user&apos;]  # 因为是注册在Blueprint上，所以endpoint 前缀为 v1 </span><br><span class="line"></span><br><span class="line">class UserScope:</span><br><span class="line">    allow_api = [&apos;v1.get_user&apos;]</span><br><span class="line"></span><br><span class="line">    # 判断当前访问的endpoint是否在scope中</span><br><span class="line">def is_in_scope(scope, endpoint):</span><br><span class="line">    # 反射获取类</span><br><span class="line">    scope = globals()[scope]()  # globals使用类的名字动态创建对象</span><br><span class="line">    if endpoint in scope.allow_api:</span><br><span class="line">        return True</span><br><span class="line">    else:</span><br><span class="line">        return False</span><br></pre></td></tr></table></figure></p>
<h4 id="1-2-生成令牌"><a href="#1-2-生成令牌" class="headerlink" title="1.2 生成令牌"></a>1.2 生成令牌</h4><p>app/models/user.py<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">@staticmethod</span><br><span class="line">def verify(email, password):</span><br><span class="line">    user = User.query.filter_by(email=email).first_or_404()   # 查询出当前用户</span><br><span class="line">    if not user.check_password(password):  # 检验密码</span><br><span class="line">        raise AuthFailed()   #抛出异常</span><br><span class="line">    scope = &apos;AdminScope&apos; if user.auth == 2 else &apos;UserScope&apos;  # 判断用户作用域，假设只有两个作用域</span><br><span class="line">    return &#123;&apos;uid&apos;: user.id,&apos;scope&apos;: scope&#125;  #成功，返回uid   # 返回scope</span><br></pre></td></tr></table></figure></p>
<p>app/api/v1/token.py<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">from app.libs.redprint import Redprint</span><br><span class="line"></span><br><span class="line">from flask import current_app</span><br><span class="line">from app.libs.enums import ClientTypeEnum</span><br><span class="line">from app.models.user import User</span><br><span class="line">from app.validators.forms import ClientForm</span><br><span class="line">from itsdangerous import TimedJSONWebSignatureSerializer as Serializer</span><br><span class="line"></span><br><span class="line">from flask import jsonify</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">api = Redprint(&apos;token&apos;) # 实例化一个Redprint</span><br><span class="line"></span><br><span class="line">@api.route(&apos;&apos;, methods=[&apos;POST&apos;])  # 路由注册</span><br><span class="line"># 返回token的试图函数，这里稍微破坏一下REST的规则，由于登录操作密码安全性较高，使用GET的话会泄漏</span><br><span class="line">def get_token():</span><br><span class="line">    form = ClientForm().validate_for_api()   # 同注册过程，不同client 区分</span><br><span class="line">    promise = &#123;</span><br><span class="line">        ClientTypeEnum.USER_EMAIL: User.verify,  #验证 # 在 user中编写 verify</span><br><span class="line">        # ClientTypeEnum.USER_MINA: __register_user_by_MINA </span><br><span class="line">    &#125;</span><br><span class="line">    # 拿到用户信息</span><br><span class="line">    identity = promise[form.type.data](</span><br><span class="line">        form.account.data,</span><br><span class="line">        form.secret.data</span><br><span class="line">    )</span><br><span class="line"></span><br><span class="line">    # 调用函数生成token</span><br><span class="line">    expiration = current_app.config[&apos;TOKEN_EXPIRATION&apos;]  #过期时间</span><br><span class="line">    token = generator_auth_token(identity[&apos;uid&apos;],</span><br><span class="line">                                form.type.data,</span><br><span class="line">                                identity[&apos;scope&apos;],</span><br><span class="line">                                expiration=expiration)</span><br><span class="line">    t = &#123;</span><br><span class="line">            &apos;token&apos;: token.decode(&apos;ascii&apos;)  # 因为是byte</span><br><span class="line">        &#125;</span><br><span class="line">    return jsonify(t), 201  # 返回 json 字典</span><br><span class="line"></span><br><span class="line">def generator_auth_token(uid, ac_type, scope=None,expiration=7200):</span><br><span class="line">    &quot;&quot;&quot;生成令牌  ，拿到uid,client类型，权限作用域，过期时间&quot;&quot;&quot;</span><br><span class="line">    s = Serializer(current_app.config[&apos;SECRET_KEY&apos;],expires_in=expiration)  # expires_in 生成令牌的有效期</span><br><span class="line">    return s.dumps(&#123;</span><br><span class="line">                    &apos;uid&apos;: uid,</span><br><span class="line">                    &apos;type&apos;: ac_type.value,</span><br><span class="line">                    &apos;scope&apos;: scope</span><br><span class="line">                &#125;)  # 将想写入的信息以字典形式写入令牌</span><br></pre></td></tr></table></figure></p>
<h4 id="1-3-验证令牌"><a href="#1-3-验证令牌" class="headerlink" title="1.3 验证令牌"></a>1.3 验证令牌</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"># 编写一个验证token的装饰器</span><br><span class="line"></span><br><span class="line">from flask_httpauth import HTTPBasicAuth</span><br><span class="line"></span><br><span class="line">from flask import current_app, g, request</span><br><span class="line">from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature, \</span><br><span class="line">          SignatureExpired</span><br><span class="line"></span><br><span class="line">from collections import namedtuple</span><br><span class="line"></span><br><span class="line">from app.libs.erro_code import AuthFailed, Forbidden</span><br><span class="line">from app.libs.scope import is_in_scope</span><br><span class="line"></span><br><span class="line">auth = HTTPBasicAuth()</span><br><span class="line"></span><br><span class="line">User = namedtuple(&apos;User&apos;, [&apos;uid&apos;, &apos;ac_type&apos;, &apos;scope&apos;])</span><br><span class="line"></span><br><span class="line"># @auth.verify_password</span><br><span class="line"># def verify_password(account, password):</span><br><span class="line"></span><br><span class="line">#   # 需要在HTTP请求的头部设置一个固定的键值对</span><br><span class="line">#   # key=Authorization,value=basic base64(account:psd)</span><br><span class="line">#   #    imwl@live.com:12345678   编码后 aW13bEBsaXZlLmNvbToxMjM0NTY3OA==</span><br><span class="line">#   #  key=Authorization,value=basic aW13bEBsaXZlLmNvbToxMjM0NTY3OA==</span><br><span class="line">#     return True</span><br><span class="line"></span><br><span class="line">@auth.verify_password</span><br><span class="line">def verify_password(token, password):</span><br><span class="line">    user_info =  verify_auth_token(token) # token 赋值给 user_info</span><br><span class="line">    if not user_info:</span><br><span class="line">        return False</span><br><span class="line">    else:</span><br><span class="line">        g.user = user_info  # g 变量 ,代理模式</span><br><span class="line">        return True</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def verify_auth_token(token):</span><br><span class="line">    s = Serializer(current_app.config[&apos;SECRET_KEY&apos;])</span><br><span class="line">    try:</span><br><span class="line">        data = s.loads(token)   # 解密 token</span><br><span class="line">    # token不合法抛出的异常</span><br><span class="line">    except BadSignature:</span><br><span class="line">        raise AuthFailed(msg=&apos;token is valid&apos;, erro_code=1002)</span><br><span class="line">    # token过期抛出的异常</span><br><span class="line">    except SignatureExpired:</span><br><span class="line">        raise AuthFailed(msg=&apos;token is expired&apos;, erro_code=1003)</span><br><span class="line"></span><br><span class="line">    uid = data[&apos;uid&apos;]</span><br><span class="line">    ac_type = data[&apos;type&apos;]   # 生成令牌的时候写入了 uid ac_type</span><br><span class="line">    scope = data[&apos;scope&apos;]</span><br><span class="line">    # 也可在这拿到当前request的视图函数</span><br><span class="line">    allow = is_in_scope(scope ,request.endpoint) # request.endpoint  拿到当前视图函数的endpoint 判断是否有权限。</span><br><span class="line">    if not allow:</span><br><span class="line">        raise Forbidden()</span><br><span class="line">    return User(uid, ac_type, scope)   # 定义对象式 接口返回回去 ,scope 先返回为空字符串</span><br></pre></td></tr></table></figure>
<h1 id="7-4-Scope优化"><a href="#7-4-Scope优化" class="headerlink" title="7.4 Scope优化"></a>7.4 Scope优化</h1><h4 id="1-支持权限相加"><a href="#1-支持权限相加" class="headerlink" title="1.支持权限相加"></a>1.支持权限相加</h4><p>假如我们的UserScope的权限是A，B，C。而AdminScope的权限是A，B，C，D。按照我们的写法，我们的A，B，C就需要些两遍。况且这只是一个简单的例子，实际情况下会更复杂。所以我们需要实现一种方法，可以让AdminScope的allow_api可以和UserScope的allow_api相加得到新的allow_api。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">class UserScope:</span><br><span class="line">    allow_api = [&apos;v1.A&apos;,&apos;v1.B&apos;]</span><br><span class="line"></span><br><span class="line">class SuperScope:    # 相加操作</span><br><span class="line">    allow_api = [&apos;v1.C&apos;,&apos;v1.D&apos;]</span><br><span class="line"></span><br><span class="line">    def __init__(self):</span><br><span class="line">        self.add(UserScope())</span><br><span class="line"># 这个方法可以将其他的Scope合并到当前Scope。省去重复代码的编写</span><br><span class="line">    def add(self, other):</span><br><span class="line">        self.allow_api = self.allow_api + other.allow_api</span><br></pre></td></tr></table></figure>
<h4 id="2-支持权限链式相加"><a href="#2-支持权限链式相加" class="headerlink" title="2.支持权限链式相加"></a>2.支持权限链式相加</h4><p>现在我们只能讲AdminScope和UserScope的权限相加，如果还想再加上其他的Scope，就需要链式的操作<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">class AdminScope:</span><br><span class="line">    allow_api = [&apos;v1.super_get_user&apos;]  # 因为是注册在Blueprint上，所以endpoint 前缀为 v1 </span><br><span class="line"></span><br><span class="line">class UserScope:</span><br><span class="line">    allow_api = [&apos;v1.A&apos;,&apos;v1.B&apos;]</span><br><span class="line"></span><br><span class="line">class SuperScope:    # 相加操作</span><br><span class="line">    allow_api = [&apos;v1.C&apos;,&apos;v1.D&apos;]</span><br><span class="line"></span><br><span class="line">    def __init__(self):</span><br><span class="line">        self.add(UserScope()).add(AdminScope())</span><br><span class="line">        </span><br><span class="line"></span><br><span class="line">    def add(self, other):</span><br><span class="line">        self.allow_api = self.allow_api + other.allow_api</span><br><span class="line">        return self  # 将self return不然第二段调用为None.add(),报错</span><br></pre></td></tr></table></figure></p>
<h4 id="3-所有子类支持相加"><a href="#3-所有子类支持相加" class="headerlink" title="3.所有子类支持相加"></a>3.所有子类支持相加</h4><p>add方法不应该写在具体的Scope类中，因为这样就只有当前Scope类有该功能了。应该将add方法写在基类Scope中<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">class Scope:</span><br><span class="line">    allow_api = []</span><br><span class="line"></span><br><span class="line">    def add(self, other):</span><br><span class="line">        self.allow_api = self.allow_api + other.allow_api</span><br><span class="line">        return self</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class AdminScope(Scope):</span><br><span class="line">    allow_api = [&apos;v1.super_get_user&apos;]  # 因为是注册在Blueprint上，所以endpoint 前缀为 v1 </span><br><span class="line">    def __init__(self):</span><br><span class="line">        self.add(UserScope())</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class UserScope(Scope):</span><br><span class="line">    allow_api = [&apos;v1.A&apos;,&apos;v1.B&apos;]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class SuperScope(Scope):    # 相加操作</span><br><span class="line">    allow_api = [&apos;v1.C&apos;,&apos;v1.D&apos;]</span><br><span class="line"></span><br><span class="line">    def __init__(self):</span><br><span class="line">        self.add(UserScope()).add(AdminScope())</span><br><span class="line">        </span><br><span class="line">#  重复问题，得去重SuperScope为[&apos;v1.C&apos;, &apos;v1.D&apos;, &apos;v1.A&apos;, &apos;v1.B&apos;, &apos;v1.super_get_user&apos;, &apos;v1.A&apos;, &apos;v1.B&apos;]</span><br><span class="line">#  要是能直接相加就好了      self + UserScope() + AdminScope()</span><br></pre></td></tr></table></figure></p>
<h4 id="4-运算符重载"><a href="#4-运算符重载" class="headerlink" title="4.运算符重载"></a>4.运算符重载</h4><p>现在我们一直使用add()方法，太啰嗦了，我们可以修改我们的代码，使得我们可以使用+号来完成add()方法的功能。 要完成这个功能，就要使用到运算符重载的技术<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">class Scope:</span><br><span class="line">    allow_api = []</span><br><span class="line">    # def add(self, other):</span><br><span class="line"># 运算符重载，支持对象相加操作</span><br><span class="line">    def __add__(self, other):</span><br><span class="line">        self.allow_api = self.allow_api + other.allow_api</span><br><span class="line">        return self</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class AdminScope(Scope):</span><br><span class="line">    allow_api = [&apos;v1.super_get_user&apos;]  # 因为是注册在Blueprint上，所以endpoint 前缀为 v1 </span><br><span class="line">    def __init__(self):</span><br><span class="line">        self + UserScope()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class UserScope(Scope):</span><br><span class="line">    allow_api = [&apos;v1.A&apos;,&apos;v1.B&apos;]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class SuperScope(Scope):    # 相加操作</span><br><span class="line">    allow_api = [&apos;v1.C&apos;,&apos;v1.D&apos;]</span><br><span class="line"></span><br><span class="line">    def __init__(self):</span><br><span class="line">        self + UserScope() + AdminScope()</span><br></pre></td></tr></table></figure></p>
<h4 id="5-去重"><a href="#5-去重" class="headerlink" title="5.去重"></a>5.去重</h4><p>我们现在的scope，编写完成之后，由于可能会连续相加，会有很多重复的试图函数，如SuperScope()中会出现两次v1.A,现在我们就需要将这些重复的试图函数去除掉。我们只需要使用set这个数据结构，就可以完成。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">class Scope:</span><br><span class="line">    allow_api = []</span><br><span class="line">    # def add(self, other):</span><br><span class="line"># 运算符重载，支持对象相加操作</span><br><span class="line">    def __add__(self, other):</span><br><span class="line">        self.allow_api = self.allow_api + other.allow_api</span><br><span class="line">        self.allow_api = list(set(self.allow_api)) # 先转化为set，后转为list 从而去重</span><br><span class="line">        return self</span><br></pre></td></tr></table></figure></p>
<p>也可以直接定义的时候，就定义成集合,例如：<code>allow_api = {&#39;v1.C&#39;,&#39;v1.D&#39;}</code></p>
<p>以上全部代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">class Scope:</span><br><span class="line">    allow_api = []</span><br><span class="line">    # def add(self, other):</span><br><span class="line"># 运算符重载，支持对象相加操作</span><br><span class="line">    def __add__(self, other):</span><br><span class="line">        self.allow_api = self.allow_api + other.allow_api</span><br><span class="line">        self.allow_api = list(set(self.allow_api)) # 先转化为set，后转为list 从而去重</span><br><span class="line">        return self</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class AdminScope(Scope):</span><br><span class="line">    allow_api = [&apos;v1.super_get_user&apos;]  # 因为是注册在Blueprint上，所以endpoint 前缀为 v1 </span><br><span class="line">    def __init__(self):</span><br><span class="line">        self + UserScope()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class UserScope(Scope):</span><br><span class="line">    allow_api = [&apos;v1.A&apos;,&apos;v1.B&apos;]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class SuperScope(Scope):    # 相加操作</span><br><span class="line">    allow_api = [&apos;v1.C&apos;,&apos;v1.D&apos;]</span><br><span class="line"></span><br><span class="line">    def __init__(self):</span><br><span class="line">        self + UserScope() + AdminScope()</span><br><span class="line"></span><br><span class="line">        </span><br><span class="line">   # 判断当前访问的endpoint是否在scope中</span><br><span class="line">def is_in_scope(scope, endpoint):</span><br><span class="line">    # 反射获取类</span><br><span class="line">    scope = globals()[scope]()  # globals使用类的名字动态创建对象</span><br><span class="line">    if endpoint in scope.allow_api:</span><br><span class="line">        return True</span><br><span class="line">    else:</span><br><span class="line">        return False</span><br></pre></td></tr></table></figure></p>
<h4 id="6-模块级别的Scope"><a href="#6-模块级别的Scope" class="headerlink" title="6.模块级别的Scope"></a>6.模块级别的Scope</h4><p>现在我们的Scope都是试图函数级别的，加入我们的user下面有100个试图函数，我们就需要把这100个全都加入进来，我们可以想办法，让我们的Scope支持可以添加一个模块下的视图函数。</p>
<p>我们可以添加一个变量，allow_moudle，来标示允许通过的模块。然后现在我们的is_in_scope只是简单的判断endpoint是否在scope.allow_api中，endpoint默认的形式是blueprint.view_func 的形式，我们可以自定义endpoint为blueprint.moudle_name+view_func这样的形式，这样我们我们就可以在is_in_scope进行模块的判断</p>
<p>修改红图的注册：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line">class Scope:</span><br><span class="line">    allow_api = []</span><br><span class="line">    allow_moudle = []</span><br><span class="line">    # def add(self, other):</span><br><span class="line"># 运算符重载，支持对象相加操作</span><br><span class="line">    def __add__(self, other):</span><br><span class="line">        self.allow_api = self.allow_api + other.allow_api</span><br><span class="line">        self.allow_api = list(set(self.allow_api)) # 先转化为set，后转为list 从而去重</span><br><span class="line">        return self</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class AdminScope(Scope):</span><br><span class="line">    allow_api = [&apos;v1.super_get_user&apos;]  # 因为是注册在Blueprint上，所以endpoint 前缀为 v1 </span><br><span class="line">    def __init__(self):</span><br><span class="line">        self + UserScope()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class UserScope(Scope):</span><br><span class="line">    allow_api = [&apos;v1.A&apos;,&apos;v1.B&apos;]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class SuperScope(Scope):    # 相加操作</span><br><span class="line">    allow_api = [&apos;v1.C&apos;,&apos;v1.D&apos;]</span><br><span class="line">    allow_moudle = [&apos;v1.user&apos;]</span><br><span class="line"></span><br><span class="line">    def __init__(self):</span><br><span class="line">        self + UserScope() + AdminScope()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        </span><br><span class="line"></span><br><span class="line">    # def add(self, other):</span><br><span class="line">    #     self.allow_api = self.allow_api + other.allow_api</span><br><span class="line">    #     return self  # 将self return不然第二段调用为None.add(),报错</span><br><span class="line"># 提取到基类中，每个都继承这个基类</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    # 判断当前访问的endpoint是否在scope中</span><br><span class="line">def is_in_scope(scope, endpoint):</span><br><span class="line">    # 反射获取类</span><br><span class="line">    scope = globals()[scope]()  # globals使用类的名字动态创建对象</span><br><span class="line">    splits = endpoint.split(&apos;+&apos;)</span><br><span class="line">    red_name = splits[0]</span><br><span class="line">    if endpoint in scope.allow_api:</span><br><span class="line">        return True</span><br><span class="line">    # v1.view_func  改为v1.moudle_name+view_func  # 改写endpoint</span><br><span class="line">    # 从Redprint 入手  v1.red_name +view_func</span><br><span class="line">    &apos;&apos;&apos;</span><br><span class="line">    从   endpoint = options.pop(&quot;endpoint&quot;, f.__name__)</span><br><span class="line">    改为 endpoint = self.name + &apos;+&apos; + options.pop(&quot;endpoint&quot;, f.__name__) # 改成Redprint+视图函数名字</span><br><span class="line">            &apos;&apos;&apos;</span><br><span class="line">    if red_name in scope.allow_moudle:</span><br><span class="line">        return True</span><br><span class="line">    else:</span><br><span class="line">        return False</span><br></pre></td></tr></table></figure></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line">class Scope:</span><br><span class="line">    allow_api = []</span><br><span class="line">    allow_moudle = []</span><br><span class="line">    # def add(self, other):</span><br><span class="line"># 运算符重载，支持对象相加操作</span><br><span class="line">    def __add__(self, other):</span><br><span class="line">        self.allow_api = self.allow_api + other.allow_api</span><br><span class="line">        self.allow_api = list(set(self.allow_api)) # 先转化为set，后转为list 从而去重</span><br><span class="line"></span><br><span class="line">        self.allow_moudle = self.allow_moudle + other.allow_moudle</span><br><span class="line">        self.allow_moudle = list(set(self.allow_moudle))   # 模块级别的相加操作</span><br><span class="line">        return self</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class AdminScope(Scope):</span><br><span class="line">    allow_api = [&apos;v1.user+super_get_user&apos;,&apos;v1.user+super_delete_user&apos;]  # 因为是注册在Blueprint上，所以endpoint 前缀为 v1 </span><br><span class="line">    </span><br><span class="line">    # allow_moudle = [&apos;v1.user&apos;]</span><br><span class="line">    def __init__(self):</span><br><span class="line">        self + UserScope()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class UserScope(Scope):</span><br><span class="line">    allow_api = [&apos;v1.user+get_user&apos;,&apos;v1.user+delete_user&apos;]</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># class SuperScope(Scope):    # 相加操作</span><br><span class="line">#     allow_api = [&apos;v1.C&apos;,&apos;v1.D&apos;]</span><br><span class="line">#     allow_moudle = [&apos;v1.user&apos;]</span><br><span class="line"></span><br><span class="line">#     def __init__(self):</span><br><span class="line">#         self + UserScope() + AdminScope()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        </span><br><span class="line"></span><br><span class="line">    # def add(self, other):</span><br><span class="line">    #     self.allow_api = self.allow_api + other.allow_api</span><br><span class="line">    #     return self  # 将self return不然第二段调用为None.add(),报错</span><br><span class="line"># 提取到基类中，每个都继承这个基类</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    # 判断当前访问的endpoint是否在scope中</span><br><span class="line">def is_in_scope(scope, endpoint):</span><br><span class="line">    # 反射获取类</span><br><span class="line">    scope = globals()[scope]()  # globals使用类的名字动态创建对象</span><br><span class="line">    splits = endpoint.split(&apos;+&apos;)</span><br><span class="line">    red_name = splits[0]</span><br><span class="line">    if endpoint in scope.allow_api:</span><br><span class="line">        return True</span><br><span class="line">    # v1.view_func  改为v1.moudle_name+view_func  # 改写endpoint</span><br><span class="line">    # 从Redprint 入手  v1.red_name +view_func</span><br><span class="line">    &apos;&apos;&apos;</span><br><span class="line">    从   endpoint = options.pop(&quot;endpoint&quot;, f.__name__)</span><br><span class="line">    改为 endpoint = self.name + &apos;+&apos; + options.pop(&quot;endpoint&quot;, f.__name__) # 改成Redprint+视图函数名字</span><br><span class="line">            &apos;&apos;&apos;</span><br><span class="line">    if red_name in scope.allow_moudle:</span><br><span class="line">        return True</span><br><span class="line">    else:</span><br><span class="line">        return False</span><br></pre></td></tr></table></figure>
<p><strong>模块级别的权限控制一定得特别注意</strong></p>
<h4 id="7-支持排除"><a href="#7-支持排除" class="headerlink" title="7.支持排除"></a>7.支持排除</h4><p>如果一个模块又100个视图函数，UserScope需要访问98个，AdminScope需要访问所有，那么UserScope的编写就太麻烦了，我们可以让我们的Scope 支持排除操作，这样UserScope就可以添加AdminScope的全部，然后再排除掉他不能访问的两个就好了<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">class Scope:</span><br><span class="line">    allow_api = []</span><br><span class="line">    allow_moudle = []</span><br><span class="line">    forbidden = []</span><br><span class="line">    # def add(self, other):</span><br><span class="line"># 运算符重载，支持对象相加操作</span><br><span class="line">    def __add__(self, other):</span><br><span class="line">        self.allow_api = self.allow_api + other.allow_api</span><br><span class="line">        self.allow_api = list(set(self.allow_api)) # 先转化为set，后转为list 从而去重</span><br><span class="line"></span><br><span class="line">        self.allow_moudle = self.allow_moudle + other.allow_moudle</span><br><span class="line">        self.allow_moudle = list(set(self.allow_moudle))   # 模块级别的相加操作</span><br><span class="line"></span><br><span class="line">        self.forbidden = self.forbidden + other.forbidden</span><br><span class="line">        self.forbidden = list(set(self.forbidden)) </span><br><span class="line">        return self</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class AdminScope(Scope):</span><br><span class="line">    # allow_api = [&apos;v1.user+super_get_user&apos;,&apos;v1.user+super_delete_user&apos;]  # 因为是注册在Blueprint上，所以endpoint 前缀为 v1 </span><br><span class="line">    </span><br><span class="line">    allow_moudle = [&apos;v1.user&apos;]</span><br><span class="line">    # def __init__(self):</span><br><span class="line">    #     self + UserScope()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class UserScope(Scope):</span><br><span class="line">    forbidden =  [&apos;v1.user+super_get_user&apos;,&apos;v1.user+super_delete_user&apos;]</span><br><span class="line">    # allow_api = [&apos;v1.user+get_user&apos;,&apos;v1.user+delete_user&apos;]</span><br><span class="line">    def __init__(self):</span><br><span class="line">        self + AdminScope()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># class SuperScope(Scope):    # 相加操作</span><br><span class="line">#     allow_api = [&apos;v1.C&apos;,&apos;v1.D&apos;]</span><br><span class="line">#     allow_moudle = [&apos;v1.user&apos;]</span><br><span class="line"></span><br><span class="line">#     def __init__(self):</span><br><span class="line">#         self + UserScope() + AdminScope()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        </span><br><span class="line"></span><br><span class="line">    # def add(self, other):</span><br><span class="line">    #     self.allow_api = self.allow_api + other.allow_api</span><br><span class="line">    #     return self  # 将self return不然第二段调用为None.add(),报错</span><br><span class="line"># 提取到基类中，每个都继承这个基类</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    # 判断当前访问的endpoint是否在scope中</span><br><span class="line">def is_in_scope(scope, endpoint):</span><br><span class="line">    # 反射获取类</span><br><span class="line">    scope = globals()[scope]()  # globals使用类的名字动态创建对象</span><br><span class="line">    splits = endpoint.split(&apos;+&apos;)</span><br><span class="line">    red_name = splits[0]</span><br><span class="line">    if endpoint in scope.forbidden:   # 排除</span><br><span class="line">        return False</span><br><span class="line"></span><br><span class="line">    if endpoint in scope.allow_api:</span><br><span class="line">        return True</span><br><span class="line">    # v1.view_func  改为v1.moudle_name+view_func  # 改写endpoint</span><br><span class="line">    # 从Redprint 入手  v1.red_name +view_func</span><br><span class="line">    &apos;&apos;&apos;</span><br><span class="line">    从   endpoint = options.pop(&quot;endpoint&quot;, f.__name__)</span><br><span class="line">    改为 endpoint = self.name + &apos;+&apos; + options.pop(&quot;endpoint&quot;, f.__name__) # 改成Redprint+视图函数名字</span><br><span class="line">            &apos;&apos;&apos;</span><br><span class="line">    if red_name in scope.allow_moudle:</span><br><span class="line">        return True</span><br><span class="line">    else:</span><br><span class="line">        return False</span><br><span class="line"># 首先判断是否在要排除的列表里</span><br></pre></td></tr></table></figure></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/flask-api/Flask构建可扩展的RESTful-API-8--补充完善/" rel="next" title="Flask构建可扩展的RESTful-API-8--补充完善">
                <i class="fa fa-chevron-left"></i> Flask构建可扩展的RESTful-API-8--补充完善
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/flask-api/Flask构建可扩展的RESTful-API-6--模型对象的序列化/" rel="prev" title="Flask构建可扩展的RESTful-API-6--模型对象的序列化">
                Flask构建可扩展的RESTful-API-6--模型对象的序列化 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.png" alt="WeiLai">
            
              <p class="site-author-name" itemprop="name">WeiLai</p>
              <p class="site-description motion-element" itemprop="description">好学近乎知，力行近乎仁，知耻近乎勇</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">132</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/itswl" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:imwl@live.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/6aa4c1b2a4a4" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-book"></i>简书</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.facebook.com/profile.php?id=100021764796181" target="_blank" title="Facebook">
                      
                        <i class="fa fa-fw fa-facebook"></i>Facebook</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#7-1-删除模型的注意事项"><span class="nav-number">1.</span> <span class="nav-text">7.1 删除模型的注意事项</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#7-2-权限管理方案"><span class="nav-number">2.</span> <span class="nav-text">7.2 权限管理方案</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-不太好的权限管理方案"><span class="nav-number">2.0.1.</span> <span class="nav-text">1.不太好的权限管理方案</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-比较好的权限管理方案"><span class="nav-number">2.0.2.</span> <span class="nav-text">2.比较好的权限管理方案</span></a></li></ol></li></ol><li class="nav-item nav-level-1"><a class="nav-link" href="#7-3-Scope权限管理的实现"><span class="nav-number">3.</span> <span class="nav-text">7.3 Scope权限管理的实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#遇到的坑"><span class="nav-number">3.1.</span> <span class="nav-text">遇到的坑</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-编码实现"><span class="nav-number">3.1.1.</span> <span class="nav-text">1.编码实现</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-scope配置"><span class="nav-number">3.1.1.1.</span> <span class="nav-text">1.1 scope配置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-生成令牌"><span class="nav-number">3.1.1.2.</span> <span class="nav-text">1.2 生成令牌</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3-验证令牌"><span class="nav-number">3.1.1.3.</span> <span class="nav-text">1.3 验证令牌</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#7-4-Scope优化"><span class="nav-number">4.</span> <span class="nav-text">7.4 Scope优化</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-支持权限相加"><span class="nav-number">4.0.0.1.</span> <span class="nav-text">1.支持权限相加</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-支持权限链式相加"><span class="nav-number">4.0.0.2.</span> <span class="nav-text">2.支持权限链式相加</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-所有子类支持相加"><span class="nav-number">4.0.0.3.</span> <span class="nav-text">3.所有子类支持相加</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-运算符重载"><span class="nav-number">4.0.0.4.</span> <span class="nav-text">4.运算符重载</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-去重"><span class="nav-number">4.0.0.5.</span> <span class="nav-text">5.去重</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-模块级别的Scope"><span class="nav-number">4.0.0.6.</span> <span class="nav-text">6.模块级别的Scope</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#7-支持排除"><span class="nav-number">4.0.0.7.</span> <span class="nav-text">7.支持排除</span></a></li></ol></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">WeiLai</span>

  
</div>


  <!--<div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>

-->



        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

  
</body>
</html>
